﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using AssetBundleHelper;

namespace HotUI{

	public class UIViewMgr:SingleClass<UIViewMgr>{
		public UIRoot root;
		public bool isInited{
			get{
				return root != null;
			}
		}
		public Dictionary<string,LuaView> views = new Dictionary<string, LuaView>();

//		List<Command> commands = new List<Command>();
		public LuaView OpenView(string name,int depth,object data){
			return onOpenView (name, depth,data);
		}
		public void CloseView(string name){
			onCloseView (name);
		}
		public LuaView getView(string name){
			if (!views.ContainsKey (name)) {
				OpenView (name,0,null);
			}
			return views [name];
		}

		public override void Begin ()
		{
			base.Begin ();
			GameTool.LoadObject ("UIRoot", null, delegate(ABObject obj) {
				var go = obj.gameObject;
				root = go.GetComponent<UIRoot>();	
				GameObject.DontDestroyOnLoad(go);
//				for(var i = 0;i < commands.Count;i++){
//					commands[i].Execute();
//				}
//				commands.Clear();
			},"Prefab/",0);
		}
		LuaView onOpenView(string name,int depth,object data){
			if (!views.ContainsKey (name))
				CreateView (name);
			views [name].SetDepth (depth);
			views [name].gameObject.SetActive (true);
			views [name].OnTryOpen (data);
			return views[name];
		}
		void onCloseView(string name){
			views [name].gameObject.SetActive (false);
			if (views.ContainsKey (name))
				views [name].OnClose ();
		}

		void CreateView(string name){
			var obj = new GameObject (name);
			obj.transform.parent = root.transform;
			obj.transform.localPosition = Vector3.zero;
			obj.transform.localScale = Vector3.one;
			obj.transform.localEulerAngles = Vector3.zero;
			var view = obj.AddComponent<LuaView> ();
			view.Init (name);
			views.Add (name, view);
		}
	}
}